package logic

import (
	"context"
	"errors"
	"hema-fresh/models/mysql"

	"hema-fresh/hemarpc/hemarpc"
	"hema-fresh/hemarpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type GoodAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodAddLogic {
	return &GoodAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 添加
func (l *GoodAddLogic) GoodAdd(in *hemarpc.GoodAddRequest) (*hemarpc.GoodAddResponse, error) {
	// todo: add your logic here and delete this line

	var class mysql.Class
	var findGoods mysql.Good
	Begin := mysql.DB.Begin()
	err := findGoods.FindGoodsByName(Begin, in.GoodName)
	if err != nil {
		Begin.Rollback()
		return nil, errors.New("商品已存在")
	}

	err = class.FindClassByName(Begin, in.ClassName)
	if err != nil {
		Begin.Rollback()
		class = mysql.Class{
			ClassName: in.ClassName,
		}
		err = class.ClassAdd(Begin)
		if err != nil {
			Begin.Rollback()
			return nil, errors.New("分类添加失败")

		}
	}
	var good mysql.Good
	good = mysql.Good{
		Model:     gorm.Model{ID: uint(int64(good.ID))},
		GoodName:  in.GoodName,
		GoodType:  in.GoodType,
		GoodPrice: float64(in.GoodPrice),
		GoodNum:   in.GoodNum,
		ClassId:   int64(class.ID),
	}
	err = good.GoodAdd(Begin)
	if err != nil {
		Begin.Rollback()
		return nil, err
	}
	Begin.Commit()
	return &hemarpc.GoodAddResponse{
		GoodId: int64(good.ID),
	}, nil
}
